package pers.kw.config.security;

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.stereotype.Component;
import pers.kw.config.oauth.MyParamValue;
import pers.kw.config.oauth.MyParamValueThreadLocal;

import java.util.ArrayList;

/**
 * 自定义UserDetailService
 */
@Component
public class MyUserDetailsService implements UserDetailsService {

    private static final Logger log = LoggerFactory.getLogger(MyUserDetailsService.class);

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        log.info("自定义UserDetailsService处理start...");
        MyParamValue current = MyParamValueThreadLocal.getCurrent();
        log.info("获取自定义参数信息：{}", JSON.toJSONString(current));
        //todo 通过调用接口查询用户信息，需要返回加密后的密码
        if (!"kw".equals(userName)) {
            throw new OAuth2Exception(userName + "用户不存在");
        }
        String password = new BCryptPasswordEncoder().encode("kw");
        return new User(
                userName,
                password,
                new ArrayList<>(2));
    }
}
